const pool = require("./db.js");

// 用户注册
async function registerUser(user) {
  const { username, password, realName, userType, companyName, phone } = user;
  
  const [result] = await pool.execute(
    'INSERT INTO user (username, password, real_name, user_type, company_name, phone, is_verified) VALUES (?, ?, ?, ?, ?, ?, ?)',
    [username, password, realName, userType, companyName, phone, userType === 'admin' ? 1 : 0]
  );
  return result.insertId;
}

// 用户登录验证
async function verifyUserLogin(username, password) {
  const [rows] = await pool.execute('SELECT * FROM user WHERE username = ? AND password = ?', [username, password]);
  if (rows.length === 0) return null;
  
  const user = rows[0];
  return user;
}

// 获取用户列表（管理员使用）
async function getAllUsers() {
  const [rows] = await pool.execute('SELECT * FROM user');
  return rows;
}

// 更新用户状态（审核/冻结）
async function updateUserStatus(userId, isVerified) {
  const [result] = await pool.execute(
    'UPDATE user SET is_verified = ? WHERE id = ?',
    [isVerified, userId]
  );
  return result.affectedRows > 0;
}

module.exports = {
  registerUser,
  verifyUserLogin,
  getAllUsers,
  updateUserStatus
};